package com.cote.douhahou.pretloan.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.cote.douhahou.pretloan.any.util.AkomapalendAnalyticsUtil;
import com.cote.douhahou.pretloan.beans.AppAkomapalendConfigCustomize;
import com.cote.douhahou.pretloan.beans.LnLiAkomapalendmitInfo;
import com.cote.douhahou.pretloan.beans.ProcessInAkomapalendfo;
import com.cote.douhahou.pretloan.msg.MessageActivity;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.service.CusServiceAkomapalendDialog;
import com.cote.douhahou.pretloan.status.BaseAkomapalendLnFragment;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.apply.LoanApplyActivity;
import com.cote.douhahou.pretloan.R;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeFragment extends BaseAkomapalendLnFragment implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    private SwipeRefreshLayout refreshLayout;
    private ImageButton customerserviceIb;
    private TextView amountTv, termTv;
    private View applyBtn, processView;

    private Runnable processRunnable;

    private final Runnable applyRunnable = () -> {

        HttpHelper.inst().submitEvent("HOME","APPLY_CLICK","");

        String[] homePermissions = AppAkomapalendConfigCustomize.instance().getHomePermission_akomapalend();

        if (AkomapaLendUtil.permissionsHasAgree(requireActivity(), homePermissions)) {
            //device info upload
            try {
                if (AkomapaLendUtil.hasLogin()) {
                    AkomapalendAnalyticsUtil.INSTANCE.saveDeviceS2SInfo();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //申请流程
            processRunnable = () -> {
                //无流程:跳转到申请页
                if (ProcessInAkomapalendfo.instance().getSteps_akomapalend().isEmpty())
                    startActivity(new Intent(requireActivity(), LoanApplyActivity.class));
                //有流程:跳转到流程页
                else startActivity(new Intent(requireContext(), MessageActivity.class));
            };

            HttpHelper.inst().process(requireActivity(),this::processResponse);

        } else
            EasyPermissions.requestPermissions(this, getString(R.string.request_permission_all), AkomapaLendConfigs.PermissionCHome, homePermissions);

    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        refreshLayout = view.findViewById(R.id.fha_refreshlayout);
        customerserviceIb = view.findViewById(R.id.fha_ib_customer_service);
        amountTv = view.findViewById(R.id.fha_tv_amount);
        termTv = view.findViewById(R.id.fha_tv_term);
        applyBtn = view.findViewById(R.id.fha_btn_apply);
        processView = view.findViewById(R.id.fha_view_process);

        refreshLayout.setOnRefreshListener(() -> {
            HttpHelper.inst().submitEvent("HOME","REFRESH_CLICK","");
            refreshLayout.setRefreshing(false);
            HttpHelper.inst().process(requireActivity(),this::processResponse);
        });

        initVie_akomapalendw();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent("HOME","START","");
        HttpHelper.inst().homeAmounts(requireActivity(),this::initM_akomapalendsg);
    }

    @Override
    public void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent("HOME","END","");
    }


    @SuppressLint("SetTextI18n")
    private void initM_akomapalendsg(){
        amountTv.setText(LnLiAkomapalendmitInfo.instance().getLimitAmount_akomapalend()+" "+ LnLiAkomapalendmitInfo.instance().getCurrency_akomapalend());
        termTv.setText(AppAkomapalendConfigCustomize.instance().getHomeTerm());
    }

    private void initVie_akomapalendw(){

        customerserviceIb.setOnClickListener(v -> new CusServiceAkomapalendDialog(requireContext()).show());

        //申请
        applyBtn.setOnClickListener(v -> applyRunnable.run());

        processView.setOnClickListener(v -> {
            processRunnable = () -> new ProcessShowDialog(requireContext(),"HOME", applyRunnable).show();
            HttpHelper.inst().process(requireActivity(),this::processResponse);
        });

    }

    public void processResponse(){
        String state = ProcessInAkomapalendfo.instance().getAkomapaLendUtil();
        if (AkomapaLendUtil.stateIsChange(state)) {//刷新用户状态
            FragmentActivity activity = requireActivity();
            AkomapaLendUtil.clearState();
            activity.startActivity(new Intent(activity, HomeActivity.class));
            activity.finish();
        }else if (processRunnable !=null) {
            processRunnable.run();
            processRunnable = null;
        }else HttpHelper.inst().homeAmounts(requireActivity(),this::initM_akomapalendsg);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        applyRunnable.run();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms))
            new AppSettingsDialog.Builder(this).build().show();
    }

    @Override
    public void onRationaleAccepted(int requestCode) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

}